package com.cxyd.modules.wms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cxyd.common.page.PageData;
import com.cxyd.common.service.impl.CrudServiceImpl;
import com.cxyd.common.utils.ProcResult;
import com.cxyd.modules.api.report.LocateCount;
import com.cxyd.modules.security.user.SecurityUser;
import com.cxyd.modules.sys.dto.SysUserDTO;
import com.cxyd.modules.sys.service.SysUserService;
import com.cxyd.modules.wms.dao.LocateDao;
import com.cxyd.modules.wms.dto.LocateDTO;
import com.cxyd.modules.wms.entity.LocateEntity;
import com.cxyd.modules.wms.entity.StockEntity;
import com.cxyd.modules.wms.service.LocateService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 货位信息
 *
 * @author g_Cycle gengruyi01@163.com
 * @since 1.0.0 2023-04-27
 */
@Service
public class LocateServiceImpl extends CrudServiceImpl<LocateDao, LocateEntity, LocateDTO> implements LocateService {

    private final SysUserService userService;

    public LocateServiceImpl(SysUserService userService) {
        this.userService = userService;
    }

    @Override
    public PageData<LocateDTO> page(Map<String, Object> params) {
        final IPage<LocateEntity> page = baseDao.selectPage(
                getPage(params, "locate_id", true),
                getWrapper(params)
        );
        //2.获取用户信息
        final List<SysUserDTO> userList = userService.getList();
        //3.将creator与updater的username通过id进行绑定
        page.getRecords().forEach(entity -> {
            if (entity.getCreator() != null) {
                entity.setCreatorName(userService.getUsernameById(entity.getCreator(), userList));
            }
            if (entity.getUpdater() != null) {
                entity.setUpdaterName(userService.getUsernameById(entity.getUpdater(), userList));
            }
        });

        return getPageData(page, LocateDTO.class);
    }

    @Override
    public QueryWrapper<LocateEntity> getWrapper(Map<String, Object> params){
        String dvcNo = (String)params.get("dvcNo");
        String locateNo = (String)params.get("locateNo");
        String contNo = (String)params.get("contNo");

        QueryWrapper<LocateEntity> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(dvcNo), "dvc_no", dvcNo);
        wrapper.like(StringUtils.isNotBlank(locateNo), "locate_no", locateNo);
        wrapper.like(StringUtils.isNotBlank(contNo), "cont_no", contNo);

        wrapper.orderByAsc("locate_type");
        wrapper.orderByAsc("row_num");
        wrapper.orderByAsc("level_num");

        return wrapper;
    }

    @Override
    public ProcResult locateDisabled(Map<String, Object> params) {
        //业务逻辑...
        baseDao.procLocateDisabled(params);
        final String code = (String) params.get("code");
        final String msg = (String) params.get("msg");
        return new ProcResult().result(code, msg);
    }

    @Override
    public ProcResult lock(Map<String, Object> params) {
        ProcResult result= new ProcResult();

        try
        {
            Long userId = SecurityUser.getUser().getId();
            Date now = new Date();
            String lockType = (String) params.get("lockType");//0-解凍 1-凍結
            //
            List<String> strArray = (List<String>) params.get("locateIds");

            List<Long>  locateIds = strArray.stream()
                    .map(Long::parseLong)
                    .collect(Collectors.toList());

            //插入order_reel
            //更新库存状态
            //生成任务和WCS任务
            for(Long locateId : locateIds) {
                LocateEntity locateUpdate = baseDao.selectById(locateId);
                if(locateUpdate.getLocateSt()!=0)
                {
                    locateUpdate.setComments("貨位已分配或已使用，不允許禁用，解禁");

                }
                else
                {
                    locateUpdate.setActive(Integer.parseInt(lockType));
                }
                locateUpdate.setUpdateDate(now);
                locateUpdate.setUpdater(userId);
                baseDao.updateById(locateUpdate);

            }


            result.setCode("0");
            result.setMsg("操作成功");

        }
        catch (Exception ex)
        {
            result.setCode("-1");
            result.setMsg(ex.toString());
        }
        return result;
    }

    @Override
    public LocateCount getLocateCount(String dvcNo) {
        LocateCount result = new LocateCount();
        try{

            result.setTotal(baseDao.selectList(new QueryWrapper<LocateEntity>()
                    .eq("dvc_no",dvcNo)
                    .eq("locate_type","HW")).stream().count());
            result.setUsed(baseDao.selectList(new QueryWrapper<LocateEntity>()
                    .eq("dvc_no",dvcNo)
                    .eq("locate_type","HW")
                    .apply("cont_no <> ''")).stream().count());

        }
        catch(Exception ex)
        {
            result.setTotal(0L);
            result.setUsed(0L);
        }
        return  result;
    }

    @Override
    public LocateCount getContCount(String dvcNo) {
        LocateCount result = new LocateCount();
        try{

            result.setTotal(baseDao.selectList(new QueryWrapper<LocateEntity>()
                    .eq("dvc_no",dvcNo)
                    .eq("locate_type","HW")
                    .apply("cont_no <> ''")).stream().count());
            result.setUsed(baseDao.selectList(new QueryWrapper<LocateEntity>()
                    .eq("dvc_no",dvcNo)
                    .eq("locate_type","HW")
                    .apply("cont_no <> ''")
                    .apply("cont_no in (select cont_no from wms_stock)")).stream().count());
            result.setUnused(baseDao.selectList(new QueryWrapper<LocateEntity>()
                    .eq("dvc_no",dvcNo)
                    .eq("locate_type","HW")
                    .apply("cont_no = ''")).stream().count());

        }
        catch(Exception ex)
        {
            result.setTotal(0L);
            result.setUsed(0L);
            result.setUnused(0L);
        }
        return  result;
    }

}